package com.yifeng.repo.micro.service.server.engine.log.sqllog;

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.RegistrationBean;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * @author zyh
 */
@Slf4j
public class SqlLogRegister extends RegistrationBean {
    private final String applicationMappingPrefix;

    public SqlLogRegister(String applicationMappingPrefix, Environment environment) {
        this.applicationMappingPrefix = StringUtils.hasText(applicationMappingPrefix) ?
                applicationMappingPrefix :  environment.getProperty("spring.application.name");
        if(Strings.isNullOrEmpty(this.applicationMappingPrefix)) {
            throw new RuntimeException("应用访问前缀不能为空");
        }
    }

    @Override
    protected String getDescription() {
        return "sqlLogRegister";
    }

    @Override
    protected void register(String description, ServletContext servletContext) {
        ServletRegistration.Dynamic registration = servletContext.addServlet("SqlLogServlet", new SqlLogServlet());
        registration.addMapping("/" + applicationMappingPrefix.replaceFirst("/", "") + "/printSql");
        log.info("**** sqlLogRegister init success ****");
    }
}
